package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.kaishengit.entity.Project;
import com.kaishengit.entity.User;
import com.kaishengit.entity.UserProject;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class UserProjectDao {
	private DBHelp<UserProject> db=new DBHelp<UserProject>();
	
	public UserProject findByProjectId(String userId,String projectId){
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT t_user_id,tu.name as username,tu.password, t_project_id,tp.name,tp.desc,tp.createtime,role FROM t_user_project AS tup");
		sql.append("LEFT JOIN t_user AS tu ON tup.t_user_id=tu.id ");
		sql.append("LEFT JOIN t_project AS tp ON tup.t_project_id=tp.id");
		sql.append("WHERE tup.t_project_id=? AND tup.t_user_id=? ");
		return db.executeQueryForObject(sql.toString(),new UserProjectRowMapper(),userId,projectId);
	}
	private class UserProjectRowMapper implements RowMapper<UserProject>{

		public UserProject mapRow(ResultSet rs) throws SQLException {
			UserProject up=new UserProject();
			up.setRole(rs.getString("role"));
			
			User user=new User();
			user.setId(rs.getString("it_user_id"));
			user.setName(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			
		    up.setUser(user);
		    up.setUserId(rs.getString("t_user_id"));
		    
		    Project p=new Project();
		    p.setId(rs.getString("t_project_id"));
		    p.setName(rs.getString("name"));
		    p.setDesc(rs.getString("desc"));
		    p.setCreatetime(rs.getString("createtime"));
		    
		    up.setProject(p);
		    up.setProjectId(rs.getString("t_project_id"));
		    
		    return up;
		}
	}

	public void save(UserProject up){
		String sql="INSERT INTO t_user_project(t_user_id,t_project_id,role)VALUES(?,?,?)";
		db.executeSQL(sql, up.getUserId(),up.getProjectId(),up.getRole());
	}
	
	
}
